﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCServer.Entities.Commands;
using IRCServer.Entities;
using IRCServer.Utilities;
using IRCServer.Backend;
using System.Threading;

namespace IRCServer.CommandHandlers
{
    class NICKCommandHandler : UserRegistrationCommandHandler
    {
        public override string HandleCommand(IRCCommandBase command, SessionBase session)
        {
            if (command is NICKCommand)
            {
                NICKCommand nickCommand = (NICKCommand)command;
                ClientSession clientSession = (ClientSession)session;

                if (nickCommand.Nickname == null)
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NONICKNAMEGIVEN, string.Empty);
                }

                List<User> filteredUsers = ServerBackend.Instance.Users.Where(u => u.Nickname != null && u.Nickname.ToLower() == nickCommand.Nickname.ToLower()).ToList();

                if (filteredUsers.Count() > 0 && (clientSession.User == null || (clientSession.User != null && filteredUsers[0] != clientSession.User)))
                {
                    return Errors.GetErrorResponse(ErrorCode.ERR_NICKNAMEINUSE, nickCommand.Nickname);
                }

                if (clientSession.User != null)
                {
                    clientSession.User.Nickname = nickCommand.Nickname;
                }
                else
                {
                    clientSession.User = new User()
                    {
                        Nickname = nickCommand.Nickname
                    };

                    ServerBackend.Instance.Users.Add(clientSession.User);
                }

                if (UpdateConnectionState(clientSession))
                {
                    Thread thread = new Thread(new ThreadStart(base.AddUserToDaemon));
                    thread.Start();
                }

                return String.Empty;
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}
